const WebSocket = require('ws')
const WebSocketServer = require('ws').Server
const fs = require('fs');

// const queryString = require('query-string')
// const { getConnectionData } = require('./helper')

// const getServerUrl = (url) => queryString.parse(url.split('?')[1], '&')
const server = new WebSocketServer({ port: 1234 })

/**
 * 创建一个中转服务；
 * 约定：url 中参数 url：服务器url ；type 服务器链接类型
 */
server.on('connection', function (webWs, request) {
//   const { url, type } = getServerUrl(request.url)
//   const serveWs = new WebSocket(`ws://${url}`)
//   serveWs.binaryType = 'Arraybuffer'

//   serveWs.on('open', () => serveWs.send(getConnectionData(type)))
//   serveWs.on('message', (message) => webWs.send(message))
//   serveWs.on('error', () => webWs.close())
//   serveWs.on('close', () => webWs.close())

  webWs.on('message', (message) => {
    fs.appendFileSync("./data.txt",message);
    const data = fs.readFileSync('./test.pcl');
    webWs.send(data);
  })
//   webWs.on('error', () => serveWs.close())
//   webWs.on('close', () => serveWs.close())
})
